/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package io.renren.modules.sys.controller;

import io.renren.common.utils.R;
import io.renren.modules.sys.entity.MySysUserEntity;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.form.SysLoginForm;
import io.renren.modules.sys.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;

/**
 * 登录相关
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@Api(tags = "我的登录操作")
@RequestMapping
public class SysLoginController extends AbstractController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserTokenService sysUserTokenService;
    @Autowired
    private SysCaptchaService sysCaptchaService;


    // 自定义的
    @Autowired
    private MySysCaptchaService mySysCaptchaService;
    @Autowired
    private MySysUserService mySysUserService;
    @Autowired
    private MySysUserTokenService mySysUserTokenService;

    /**
     * 验证码
     */
    @GetMapping("my-captcha.jpg")
    public void myCaptcha(HttpServletResponse response, String uuid) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //获取图片验证码
        BufferedImage image = mySysCaptchaService.getCaptcha(uuid);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);

    }


    @PostMapping("/my/sys/login")
    @ApiOperation("我的登录接口")
    @ApiImplicitParam(name = "sysLoginForm", value = "登录接口参数", dataType = "SysLoginForm", paramType = "body")
    public Map<String, Object> myLogin(@RequestBody SysLoginForm sysLoginForm) {

        boolean captcha = mySysCaptchaService.validate(sysLoginForm.getUuid(), sysLoginForm.getCaptcha());
        if (!captcha) {
            return R.error("验证码不正确");
        }
        MySysUserEntity user = mySysUserService.queryByUsername(sysLoginForm.getUsername());

        System.out.println(sysLoginForm);
        System.out.println(sysLoginForm.getUsername());
        System.out.println(user);
        if (user == null) {
            return R.error("用户不存在");
        }


        Sha256Hash sha256Hash = new Sha256Hash(sysLoginForm.getPassword(), user.getSalt());
        String s = sha256Hash.toHex();

        if (!user.getPassword().equals(s)) {
            return R.error("账号或密码不正确");
        }

        if (user.getStatus() == 0) {
            return R.error("账号已被锁定,请联系管理员");
        }

        R r = mySysUserTokenService.createToken(user.getUserId());

        System.out.println("====================22" +r );
        return r;
    }
    @PostMapping("/my/sys/logout")
    public R myLogout() {
        mySysUserTokenService.logout(getUserId());
        return R.ok();
    }


    @GetMapping("captcha.jpg")
    public void captcha(HttpServletResponse response, String uuid) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //获取图片验证码
        BufferedImage image = mySysCaptchaService.getCaptcha(uuid);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }


    /**
     * 登录
     */
    @PostMapping("/sys/login")
    public Map<String, Object> login(@RequestBody SysLoginForm form) throws IOException {
        boolean captcha = sysCaptchaService.validate(form.getUuid(), form.getCaptcha());
        if (!captcha) {
            return R.error("验证码不正确");
        }

        //用户信息
        SysUserEntity user = sysUserService.queryByUserName(form.getUsername());

        //账号不存在、密码错误
        if (user == null || !user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) {
            return R.error("账号或密码不正确");
        }

        //账号锁定
        if (user.getStatus() == 0) {
            return R.error("账号已被锁定,请联系管理员");
        }

        //生成token，并保存到数据库
        R r = sysUserTokenService.createToken(user.getUserId());
        return r;
    }


    /**
     * 退出
     */
    @PostMapping("/sys/logout")
    public R logout() {
        sysUserTokenService.logout(getUserId());
        return R.ok();
    }

}
